package run.iget.security.controller;

import java.util.Objects;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.AllArgsConstructor;
import run.iget.framework.captcha.service.CaptchaService;
import run.iget.framework.propertity.ModuleProperties;
import run.iget.security.annotation.AuthCheck;
import run.iget.security.bean.AuthUser;
import run.iget.security.bean.SafeAuthUser;
import run.iget.security.constant.SecurityConst;
import run.iget.security.req.LoginReq;
import run.iget.security.service.UserAuthService;
import run.iget.security.util.LoginUtils;

/**
 * 代码千万行，注释第一行，注释不规范，迭代两行泪
 * ---------------类描述-----------------
 * 用户登录认证控制器
 * ---------------类描述-----------------
 *
 * @author 大周
 * @since 2022/8/25 17:47
 */
@RestController
@RequestMapping("/common/oauth")
@AllArgsConstructor
@ConditionalOnProperty(prefix = SecurityConst.MODULE_NAME, value = ModuleProperties.CONDITIONAL_ON_PROPERTY_VALUE_NAME)
public class UserOauthController {

    private final CaptchaService  captchaService;
    private final UserAuthService userOauthService;

    @PostMapping("login")
    public AuthUser login(@RequestBody LoginReq req) {
        // 校验验证码，不正确则抛出异常
        if (Objects.nonNull(req.getCaptcha())) {
            captchaService.verify(req.getCaptcha());
        }
        // 登录
        SafeAuthUser authUser = userOauthService.login(req);

        // 登录状态记录
        LoginUtils.login(authUser);

        return authUser;
    }

    @PostMapping("logout")
    @AuthCheck(checkUri = false, enable = false)
    public void logout() {
        LoginUtils.loginOut();
    }
}
